package sol.cc;

import def.ListNode;
import utils.LinkedListUtils;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 编写代码，以给定值x为基准将链表分割成两部分，所有小于x的结点排在大于或等于x的结点之前
 * 给定一个链表的头指针 ListNode* pHead，请返回重新排列后的链表的头指针。注意：分割以后保持原来的数据顺序不变。
 */
public class Issue2_4 {
    public static ListNode partition(ListNode pHead, int x) {
        if (pHead == null || pHead.next == null)
            return pHead;

        ListNode before = new ListNode(0);
        ListNode after = new ListNode(0);
        ListNode beforePtr = before;
        ListNode afterPtr = after;

        while (pHead != null) {

            //先将当前元素取下
            ListNode tmp = pHead;
            pHead = pHead.next;
            tmp.next = null;

            if (tmp.val < x) {
                beforePtr.next = tmp;
                beforePtr = tmp;
            } else {
                afterPtr.next = tmp;
                afterPtr = tmp;
            }
        }

        //连接两个链表
        beforePtr.next = after.next;

        return before.next;
    }

    public static void main(String[] args) {
        ListNode head = LinkedListUtils.create(1, 4, 3, 2, 5);
        LinkedListUtils.print(head);

        head = partition(head, 3);
        LinkedListUtils.print(head);
    }
}
